import json
import socket
import threading
import chessman
import image
import pygame
from pygame.locals import *
import sys

win_img = image.Image('./pic/win.png', (0, 200), (800, 400))
lose_img = image.Image('./pic/lose.png', (0, 200), (800, 400))
list_x = [65, 115, 167, 217, 268, 319, 371, 420, 472, 523, 574, 626, 677, 729, 780]
list_y = [14, 64, 116, 167, 217, 269, 319, 373, 425, 474, 527, 578, 628, 681, 731]


def check_win(zb, single_list):
    if len(single_list) < 5:
        return False
    # 获取最后一次下子的坐标
    x, y = zb

    # 检查水平方向
    count = 0
    for piece in single_list:
        if piece[0] == x and abs(piece[1] - y) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查垂直方向
    count = 0
    for piece in single_list:
        if piece[1] == y and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查主对角线方向（右上到左下）
    count = 0
    for piece in single_list:
        if abs(piece[0] - x) == abs(piece[1] - y) and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查副对角线方向（左上到右下）
    count = 0
    for piece in single_list:
        if abs(piece[0] - x) == abs(piece[1] - y) and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    return False


def find_closest_value(target, lst):
    min_diff = float('inf')
    index = None

    for i, val in enumerate(lst):
        diff = abs(target - val)
        if diff < min_diff:
            min_diff = diff
            # closest_value = val
            index = i
    return index

# 当前是否可以下
can = True
# 游戏是否结束
finish = False

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = input("请输入服务器ip:")
c.connect((server_ip, 40001))

input_color = input("请选择棋子颜色:(1黑2白)")
if input_color == '1':
    my_color = "black"
else:
    my_color = "white"

def my_client(c: socket.socket, is_white):
    global can
    global finish
    while True:
        recv = c.recv(1024)
        if recv:
            print(recv)
            loads = json.loads(recv)

            type = loads["type"]
            zb = loads["zb"]
            if type == 0:
                finish = True
                winner = loads["winner"]
                if winner == my_color:
                    chessman_img = chessman.Chessman(f'./pic/{winner}.png', (list_x[zb[0]] - 32, list_y[zb[1]] - 32),
                                                     (64, 64))
                    chessman_img.update()
                    chessman_img.draw(DISPLAYSURF)
                    pygame.display.update()
                    win_img.update()
                    win_img.draw(DISPLAYSURF)
                    pygame.display.update()
                else:
                    print("输了")
                    lose_img.update()
                    lose_img.draw(DISPLAYSURF)
                    pygame.display.update()
                continue
            else:
                color = loads["color"]
                if color == my_color:
                    can = False
                else:
                    can = True
                chessman_img = chessman.Chessman(f'./pic/{color}.png', (list_x[zb[0]] - 32, list_y[zb[1]] - 32),
                                                 (64, 64))
                chessman_img.update()
                chessman_img.draw(DISPLAYSURF)
                pygame.display.update()




pygame.init()
# 设置棋盘大小
DISPLAYSURF = pygame.display.set_mode((800, 800))
# 设置背景颜色
DISPLAYSURF.fill((255, 255, 255))
# 加载图片对象
img_board = pygame.image.load('./pic/board.png')
DISPLAYSURF.blit(img_board, (0, 0))
pygame.display.update()
# is_white = True

threading.Thread(target=my_client, args=(c, None)).start()
while True:
    # recv = c.recv(1024)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if finish:
                continue
            if event.button != 1:
                continue
            if not can:
                continue
            x, y = pygame.mouse.get_pos()
            xx = find_closest_value(x, list_x)
            yy = find_closest_value(y, list_y)

            # 坐标
            zb = (xx, yy)
            client_msg = {
                "type": 1,
                "color": my_color,
                "zb": zb
            }

            i = c.send(json.dumps(client_msg).encode())
